import { Injectable } from '@nestjs/common';
import { UserDao as Dao } from '@/servers/daos/user/user.dao';
import { UserRoleDao } from '@/servers/daos/user/user-role.dao';
import { CacheService } from '@/servers/redis/cache/cache.service';

import { from } from 'rxjs';

@Injectable()
export class UserService {

    constructor(
        private dao: Dao,
        private cacheService: CacheService,
        private userRoleDao: UserRoleDao,
    ) { }

    /**
     * 查询所有
     */
    findAll(params: any): Promise<any> {
        return this.dao.findAll(params);
    }

    /**
     * 按条件查询
      */
    findWhere(params: any): Promise<any> {
        return this.dao.findWhere(params);
    }

    /**
    * 判断用户是否存在
    */
    async hasUser(params: any): Promise<number> {
        let user = await this.dao.findWhere({username:params.username});
        return user?1:0;
    }

    /**
     * 添加
     */
    async add(params: any): Promise<any> {
        let user = await this.dao.add(params);
        //有选择角色
        if (user && params.role_id && params.role_id > 0) {
            let obj = {
                user_id: user.id,
                role_id: params.role_id
            };
            this.userRoleDao.add(obj);
        }
        return user;
    }

    /**
     * 修改
     * @param params 
     */
    async update(params: any): Promise<any> {
        //有选择角色
        if (params.role_id && params.role_id > 0) {
            let userRole = await this.userRoleDao.findOne(params);
            let obj = {
                user_id: params.id,
                role_id: params.role_id
            };
            //判断添加或者修改
            let role_res=null;
            if (!userRole) {
                role_res=await this.userRoleDao.add(obj);
            } else {
                obj['id'] = userRole.id;
                role_res=await this.userRoleDao.update(obj);
            }
            if(!role_res){
                return '角色保存不成功';
            }else{
                return this.dao.update(params);
            }
        }else{
            return this.dao.update(params);
        }
    }

    /**
     * 删除
     * @param params 
     */
    async delete(params: any): Promise<any> {
        return this.dao.delete(params);
    }
}
